package com.ambitor.grass.sql.statement;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.commons.lang.StringUtils;

public class DefaultStatementImpl extends StatementImpl implements
		DefaultOperation {

	private String sql;

	public DefaultStatementImpl(Connection conn, String sqlstr)
			throws Exception {
		super(conn);
		this.sql = sqlstr;
	}

	public ResultSet executeQuery() throws Exception {
		ResultSet result = this.getStatement().executeQuery(this.sql);
		return result;
	}

	public int executeUpdate() throws Exception {
		int result = this.getStatement().executeUpdate(this.sql);
		return result;
	}

	@Override
	public String executeInsertAndReturnLastInsertId() throws Exception {
		this.getStatement().executeUpdate(this.sql,
				Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = this.getStatement().getGeneratedKeys();
		String autoIncKey = "";
		if (rs.next()) {
			autoIncKey = rs.getString(1);
		}
		if (StringUtils.isBlank(autoIncKey))
			throw new Exception("获取自增主键出现异常");
		return autoIncKey;
	}
}
